#include "link_list.h"

// 创建一个链表
Link_list *init_link_list(void)
{
    Link_list *list = (Link_list *)malloc(sizeof(Link_list));
    if (NULL == list)
    {
        printf("创建失败\n");
        return NULL;
    }
    list->next = NULL;
    return list;
}

// 单链表的销毁
void free_link_list(Link_list **list)
{
    if (NULL == *list)
    {
        printf("链表为空\n");
        return;
    }
    // 销毁节点
    Node *ptr1 = (*list)->next;
    Node *ptr2 = ptr1->next;
    for (size_t i = 0; ptr1 != NULL; i++)
    {
        free(ptr1);
        ptr1 = ptr2;
        if (NULL != ptr2)
        {
            ptr2 = ptr2->next;
        }  
    }
    // 销毁头节点
    free(*list);
    *list = NULL;
}

// 单链表的遍历

void print_link_list(Link_list *list)
{
    if (NULL == list)
    {
        printf("链表为空\n");
        return;
    }
    Node *ptr = list->next; // 指向第一个节点
    while (ptr != NULL)
    {
        printf("姓名:%s 性别:%s 年龄:%d 成绩:%d 学号:%d\n",
               ptr->data.name, ptr->data.sex, ptr->data.age,
               ptr->data.sco, ptr->data.id);
        ptr = ptr->next;
    }
    printf("\n");
}

// 单链表的插入
void tail_insert_link_list(Link_list *list, Elenemt_data data)
{
    if(NULL == list)
    {
        printf("链表为空\n");
        return;
    }
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (NULL == new_node)
    {
        printf("创建失败\n");
        return;
    }
    new_node->data = data;
    new_node->next = NULL;
    Node *ptr = list->next;
    while (ptr != NULL)
    {
        ptr = ptr->next;
    }
    ptr->next = new_node;

}